<template>
	<el-main class="bg table_wrap">
		<!-- 统计报表区域 -->
		<el-row :gutter="20" style="margin-bottom: 20px;">
			<el-col :xs="24" :sm="8" :lg="8">
				<el-card shadow="hover">
					<div slot="header">
						<span>收藏统计</span>
					</div>
					<div class="statistics-box">
						<div class="stat-item">
							<div class="stat-label">总收藏数</div>
							<div class="stat-value">{{ statistics.total }}</div>
						</div>
						<div class="stat-item">
							<div class="stat-label">人均收藏数</div>
							<div class="stat-value">{{ statistics.avgPerUser }}</div>
						</div>
						<div class="stat-item">
							<div class="stat-label">今日收藏</div>
							<div class="stat-value">{{ statistics.today }}</div>
						</div>
						<div class="stat-item">
							<div class="stat-label">本周收藏</div>
							<div class="stat-value">{{ statistics.thisWeek }}</div>
						</div>
						<div class="stat-item">
							<div class="stat-label">本月收藏</div>
							<div class="stat-value">{{ statistics.thisMonth }}</div>
						</div>
					</div>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="16" :lg="16">
				<el-card shadow="hover">
					<div slot="header">
						<span>收藏月度统计</span>
					</div>
					<div id="collectMonthChart" style="width: 100%; height: 300px;"></div>
				</el-card>
			</el-col>
		</el-row>
		
		<!-- 搜索表单 -->
		<el-form label-position="right" :model="query" class="form p_4" label-width="120">
			<el-row>
				<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
					<el-form-item label="标题">
						<el-input v-model="query.title"></el-input>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
					<el-form-item label="用户ID">
						<el-input-number v-model.number="query.user_id" :min="0"></el-input-number>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
					<el-form-item label="收藏时间">
						<el-date-picker
							v-model="query.date_range"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :lg="24" class="search_btn_wrap">
					<el-col :xs="24" :sm="12" :lg="12" class="search_btn_1">
						<el-form-item>
							<el-button type="primary" @click="search()" class="search_btn_find">查询</el-button>
							<el-button @click="reset()" class="search_btn_reset">重置</el-button>
						</el-form-item>
					</el-col>

				<el-col :xs="24" :sm="12" :lg="12" class="search_btn_2">
					<el-form-item>
						<el-button type="success" class="float-right" @click="exportExcel()" style="margin-right: 10px;">导出Excel</el-button>
						<el-button type="warning" class="float-right" @click="exportCSV()" style="margin-right: 10px;">导出CSV</el-button>
						<el-button v-if="user_group == '管理员' || $check_action('/collect/table','del')" class="float-right search_btn_del" type="danger" @click="delInfo()">删除</el-button>
					</el-form-item>
				</el-col>
				</el-col>
			</el-row>
		</el-form>
		
		<!-- 数据表格 -->
		<el-table border :data="list" @selection-change="selectionChange" @sort-change="$sortChange" style="width: 100%" stripe>
			<el-table-column fixed type="selection" tooltip-effect="dark" width="50">
			</el-table-column>

			<el-table-column prop="title" label="标题" min-width="200">
			</el-table-column>

			<el-table-column prop="user_id" label="用户ID" min-width="100">
			</el-table-column>

			<el-table-column prop="img" label="封面图" min-width="110">
				<template slot-scope="scope">
					<el-image
					    style="width: 100px; height: 100px"
					    :src="$fullUrl(scope.row.img)"
					    :preview-src-list="[$fullUrl(scope.row.img)]">
						<div slot="error" class="image-slot">
						  <img src="/img/error.png" style="width: 90px; height: 90px" />
						</div>
					  </el-image>
				</template>
			</el-table-column>

			<el-table-column sortable prop="create_time" label="创建时间" min-width="200">
			    <template slot-scope="scope">
			        {{ $toTime(scope.row["create_time"],"yyyy-MM-dd hh:mm:ss") }}
			    </template>
			</el-table-column>

			<el-table-column sortable prop="update_time" label="更新时间" min-width="200">
			    <template slot-scope="scope">
			        {{ $toTime(scope.row["update_time"],"yyyy-MM-dd hh:mm:ss") }}
			    </template>
			</el-table-column>

			<!-- 操作 -->
			<el-table-column fixed="right" label="操作" width="120">
				<template slot-scope="scope">
					<router-link v-if="user_group == '管理员' || $check_action('/collect/view','get')" class="el-button el-button--small is-plain el-button--primary"
						:to="'./view?' + field + '=' + scope.row[field]" size="small">
						详情
					</router-link>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页器 -->
		<div class="mt text_center">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="query.page"
			 :page-sizes="[7, 10, 30, 100]" :page-size="query.size" layout="total, sizes, prev, pager, next, jumper" :total="count">
			</el-pagination>
		</div>
		<!-- /分页器 -->
	</el-main>
</template>

<script>
	import mixin from "@/mixins/page.js";
	import LineChart from "@/components/charts/new_line_chart.vue";
	import PieChart from "@/components/charts/pie_chart.vue";
	import echarts from "@/assets/js/echarts.min.js";

	export default {
		mixins: [mixin],
		components: {
			LineChart,
			PieChart
		},
		data() {
			return {
				// 获取数据地址
				url_get_list: "~/api/collect/get_list?like=0",
				url_del: "~/api/collect/del?",

				// 字段ID
				field:"collect_id",

				// 查询
				query: {
					size: 10,
					page: 1,
					title: "",
					user_id: "",
					source_table: "",
					date_range: []
				},

				// 数据
				list: [],
				
				// 图表数据
				collectMonthChart: null,
				// 统计数据
				statistics: {
					total: 0,
					avgPerUser: 0,
					today: 0,
					thisWeek: 0,
					thisMonth: 0
				}
			}
		},
		methods: {
			deleteRow(index, rows) {
				rows.splice(index, 1);
			},

			table_class({row, column, rowIndex, columnIndex}){
				return "table_class";
			},
			
			/**
			 * 查询前处理，转换日期范围参数
			 */
			get_list_before(param) {
				// 处理日期范围
				if (param.date_range && Array.isArray(param.date_range) && param.date_range.length === 2) {
					param.create_time_min = param.date_range[0] + ' 00:00:00';
					param.create_time_max = param.date_range[1] + ' 23:59:59';
					delete param.date_range;
				}
				return param;
			},
			
			/**
			 * 处理列表数据，更新图表
			 */
			processChartData() {
				this.processStatistics();
				this.processMonthData();
			},
			
			/**
			 * 处理统计数据（从后端获取）
			 */
			async processStatistics() {
				try {
					console.log('========== 前端开始获取收藏统计数据 ==========');
					// 从后端获取统计数据
					const res = await this.$get("~/api/collect/statistics?", {});
					console.log('后端返回的完整响应:', JSON.stringify(res, null, 2));
					
					if (res.result) {
						console.log('后端返回的result对象:', JSON.stringify(res.result, null, 2));
						console.log('解析后的数据:');
						console.log('  total:', res.result.total, '类型:', typeof res.result.total);
						console.log('  avgPerUser:', res.result.avgPerUser, '类型:', typeof res.result.avgPerUser);
						console.log('  avg_per_user:', res.result.avg_per_user, '类型:', typeof res.result.avg_per_user);
						console.log('  today:', res.result.today, '类型:', typeof res.result.today);
						console.log('  thisWeek:', res.result.thisWeek, '类型:', typeof res.result.thisWeek);
						console.log('  this_week:', res.result.this_week, '类型:', typeof res.result.this_week);
						console.log('  thisMonth:', res.result.thisMonth, '类型:', typeof res.result.thisMonth);
						console.log('  this_month:', res.result.this_month, '类型:', typeof res.result.this_month);
						
						// 修复：BaseController的covertObject方法会将驼峰命名转换为下划线命名
						// 所以需要使用下划线命名来获取数据
						// 同时使用 nullish coalescing (??) 而不是 ||，避免将 0 当作 falsy 值
						const result = res.result;
						this.statistics = {
							total: (result.total !== undefined && result.total !== null) ? result.total : 0,
							// 尝试两种命名方式：驼峰和下划线
							avgPerUser: (result.avgPerUser !== undefined && result.avgPerUser !== null) 
								? result.avgPerUser 
								: ((result.avg_per_user !== undefined && result.avg_per_user !== null) ? result.avg_per_user : '0.00'),
							today: (result.today !== undefined && result.today !== null) ? result.today : 0,
							// 尝试两种命名方式：驼峰和下划线
							thisWeek: (result.thisWeek !== undefined && result.thisWeek !== null) 
								? result.thisWeek 
								: ((result.this_week !== undefined && result.this_week !== null) ? result.this_week : 0),
							// 尝试两种命名方式：驼峰和下划线
							thisMonth: (result.thisMonth !== undefined && result.thisMonth !== null) 
								? result.thisMonth 
								: ((result.this_month !== undefined && result.this_month !== null) ? result.this_month : 0)
						};
						
						console.log('设置后的statistics对象:', JSON.stringify(this.statistics, null, 2));
					} else {
						console.warn('后端返回的result为空或undefined');
						console.log('res对象:', res);
						this.statistics = {
							total: 0,
							avgPerUser: '0.00',
							today: 0,
							thisWeek: 0,
							thisMonth: 0
						};
					}
					console.log('========== 前端获取收藏统计数据完成 ==========');
				} catch (error) {
					console.error('========== 获取收藏统计数据失败 ==========');
					console.error('错误详情:', error);
					console.error('错误堆栈:', error.stack);
					this.statistics = {
						total: 0,
						avgPerUser: '0.00',
						today: 0,
						thisWeek: 0,
						thisMonth: 0
					};
				}
			},
			
			/**
			 * 处理月度统计数据（从后端获取）
			 */
			async processMonthData() {
				try {
					// 从后端获取月度统计数据
					const res = await this.$get("~/api/collect/month_statistics?", {});
					if (res.result && res.result.list) {
						const monthData = res.result.list;
						const months = monthData.map(item => item.month);
						const values = monthData.map(item => item.count);
						
						// 初始化或更新图表
						this.$nextTick(() => {
							if (!this.collectMonthChart) {
								this.collectMonthChart = echarts.init(document.getElementById('collectMonthChart'));
							}
							
							const option = {
								title: {
									text: '收藏月度统计',
									left: 'center'
								},
								tooltip: {
									trigger: 'axis',
									axisPointer: {
										type: 'shadow'
									}
								},
								xAxis: {
									type: 'category',
									data: months
								},
								yAxis: {
									type: 'value'
								},
								series: [{
									name: '收藏数量',
									type: 'bar',
									data: values,
									itemStyle: {
										color: '#409EFF'
									}
								}]
							};
							
							this.collectMonthChart.setOption(option);
						});
					}
				} catch (error) {
					console.error('获取月度统计数据失败:', error);
				}
			},
			
			/**
			 * 格式化日期
			 */
			formatDate(date) {
				if (typeof date === 'string') {
					date = new Date(date);
				}
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			/**
			 * 导出Excel
			 */
			async exportExcel() {
				try {
					this.$message.info('正在导出Excel...');
					
					// 获取所有数据（不分页）
					const allData = await this.getAllData();
					
					// 使用 xlsx 库在前端生成 Excel 文件
					let XLSX;
					try {
						XLSX = require('xlsx');
					} catch (e) {
						// 如果 require 失败，尝试动态导入
						XLSX = await import('xlsx');
					}
					
					const exportData = allData.map((item, index) => ({
						'序号': index + 1,
						'收藏ID': item.collect_id || '',
						'用户ID': item.user_id || '',
						'标题': item.title || '',
						'来源表': item.source_table || '',
						'来源ID': item.source_id || '',
						'收藏时间': this.$toTime(item.create_time, "yyyy-MM-dd hh:mm:ss") || '',
						'更新时间': this.$toTime(item.update_time, "yyyy-MM-dd hh:mm:ss") || ''
					}));
					
					const wb = XLSX.utils.book_new();
					const ws = XLSX.utils.json_to_sheet(exportData);
					XLSX.utils.book_append_sheet(wb, ws, "收藏数据");
					
					const fileName = `收藏数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
					XLSX.writeFile(wb, fileName);
					
					this.$message.success('导出成功！');
				} catch (error) {
					console.error('导出Excel失败:', error);
					this.$message.error('导出失败，请重试');
				}
			},
			
			/**
			 * 导出CSV
			 */
			async exportCSV() {
				try {
					this.$message.info('正在导出CSV...');
					
					// 获取所有数据（不分页）
					const allData = await this.getAllData();
					
					// 生成CSV内容
					const headers = ['序号', '收藏ID', '用户ID', '标题', '来源表', '来源ID', '收藏时间', '更新时间'];
					let csvContent = headers.join(',') + '\n';
					
					allData.forEach((item, index) => {
						const row = [
							index + 1,
							item.collect_id || '',
							item.user_id || '',
							`"${(item.title || '').replace(/"/g, '""')}"`,
							item.source_table || '',
							item.source_id || '',
							this.$toTime(item.create_time, "yyyy-MM-dd hh:mm:ss") || '',
							this.$toTime(item.update_time, "yyyy-MM-dd hh:mm:ss") || ''
						];
						csvContent += row.join(',') + '\n';
					});
					
					// 下载CSV文件
					const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
					const link = document.createElement('a');
					const url = URL.createObjectURL(blob);
					link.setAttribute('href', url);
					link.setAttribute('download', `收藏数据_${new Date().toISOString().slice(0, 10)}.csv`);
					link.style.visibility = 'hidden';
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
					
					this.$message.success('导出成功！');
				} catch (error) {
					console.error('导出CSV失败:', error);
					this.$message.error('导出失败，请重试');
				}
			},
			
			/**
			 * 获取所有数据（不分页）
			 */
			async getAllData() {
				const query = Object.assign({}, this.query);
				query.size = 10000; // 设置一个较大的值
				query.page = 1;
				
				// 处理日期范围
				if (query.date_range && query.date_range.length === 2) {
					query.create_time_min = query.date_range[0] + ' 00:00:00';
					query.create_time_max = query.date_range[1] + ' 23:59:59';
					delete query.date_range;
				}
				
				// 使用 $get 方法，它会自动处理 ~/ 符号
				const json = await this.$get(this.url_get_list, query);
				if (json.result && json.result.list) {
					return json.result.list;
				}
				return [];
			}
		},
		mounted() {
			// 确保数据从后端获取
			this.get_list();
			// 初始化图表（从后端获取数据）
			this.processChartData();
		}
	}
</script>

<style type="text/css">
	.bar_chart, .line_chart, .pie_chart {
		width: 100%;
		height: 300px;
	}
	
	.statistics-box {
		padding: 10px;
	}
	
	.stat-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 0;
		border-bottom: 1px solid #f0f0f0;
	}
	
	.stat-item:last-child {
		border-bottom: none;
	}
	
	.stat-label {
		font-size: 14px;
		color: #666;
	}
	
	.stat-value {
		font-size: 20px;
		font-weight: bold;
		color: #409EFF;
	}
</style>